<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发布艺术品</title>
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            background: #f8f9fa;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 600px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h2 {
            text-align: center;
            color: #333;
            margin-bottom: 20px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #555;
        }
        .form-group input, .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .form-group textarea {
            height: 150px;
            resize: vertical;
        }
        button {
            width: 100%;
            padding: 12px;
            background: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background 0.3s;
        }
        button:hover {
            background: #218838;
        }
        .message {
            margin-top: 15px;
            text-align: center;
            color: #dc3545;
        }
        .back-link {
            display: block;
            text-align: center;
            margin-top: 20px;
            color: #007bff;
            text-decoration: none;
        }
        .back-link:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>发布艺术品</h2>
        
        <div class="form-group">
            <label for="title">艺术品标题 *</label>
            <input type="text" id="title" placeholder="请输入艺术品标题">
        </div>
        
        <div class="form-group">
            <label for="description">艺术品描述</label>
            <textarea id="description" placeholder="请输入艺术品详细描述（可选）"></textarea>
        </div>
        
        <div class="form-group">
            <label for="price">价格（元）*</label>
            <input type="number" id="price" placeholder="请输入价格" min="0" step="0.01">
        </div>
        
        <div class="form-group">
            <label for="creator">创作者 *</label>
            <input type="text" id="creator" placeholder="请输入创作者姓名">
        </div>
        
        <button onclick="createArtwork()">发布艺术品</button>
        <div id="message" class="message"></div>
        <a href="artworks.html" class="back-link">返回列表</a>
    </div>
    <script>
        // 页面加载时检查登录状态
        window.onload = () => {
            checkLogin();
        };

        function createArtwork() {
            const user = checkLogin();
            if (!user) return;

            const title = document.getElementById('title').value;
            const description = document.getElementById('description').value;
            const price = document.getElementById('price').value;
            const creator = document.getElementById('creator').value;

            // 验证必填字段
            if (!title || !price || !creator) {
                document.getElementById('message').textContent = '标题、价格和创作者为必填项';
                return;
            }

            if (parseFloat(price) <= 0) {
                document.getElementById('message').textContent = '价格必须大于0';
                return;
            }

            // 关键修改：1. 用后端完整地址 2. 加 credentials: 'include' 携带跨域Cookie
            fetch('http://127.0.0.1:5000/artworks', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include', // 与后端 Access-Control-Allow-Credentials 对应
                body: JSON.stringify({
                    title,
                    description,
                    price: parseFloat(price),
                    creator,
                    owner_id: user.user_id,
                    username: user.username // 额外传username，适配后端login_required装饰器
                })
            })
            .then(res => {
                // 先判断响应是否成功，避免解析非JSON内容报错
                if (!res.ok) {
                    throw new Error(`请求失败，状态码：${res.status}`);
                }
                return res.json();
            })
            .then(data => {
                const msgEl = document.getElementById('message');
                if (data.success && data.artwork_id) {
                    msgEl.textContent = '艺术品发布成功！';
                    msgEl.style.color = '#28a745';
                    // 清空表单
                    document.getElementById('title').value = '';
                    document.getElementById('description').value = '';
                    document.getElementById('price').value = '';
                    document.getElementById('creator').value = '';
                    // 3秒后跳转到艺术品列表
                    setTimeout(() => location.href = 'artworks.html', 3000);
                } else {
                    msgEl.textContent = data.error || '发布失败';
                }
            })
            .catch(err => {
                document.getElementById('message').textContent = '发布失败：' + err.message;
            });
        }

        function checkLogin() {
            const userStr = localStorage.getItem('userInfo');
            if (!userStr) {
                alert('请先登录');
                location.href = 'login.html';
                return null;
            }
            return JSON.parse(userStr);
        }
    </script>
</body>
</html>